#include "stdafx.h"

#include "bookdata.h"
#include "cashier.h"
#include "bookCollection.h"
#include <string>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include "btree.h"
#include <algorithm>
#include <list>
#include <iomanip>

using namespace std;

void Cashier::build() {
 
  char again = ' ';
  int  qty = 0;
  string ISBN = " ";
  bool done = false;
  list<int> qtys;

  time_t t = time(0);   // get time now
  struct tm * now = localtime( & t );
  cout << (now->tm_year + 1900) << '-' 
       << (now->tm_mon + 1) << '-'
       <<  now->tm_mday
       << endl;

  while (!done) {

    
    cout << "Quantity of the book: ";
    cin  >> qty;
    
    cout << "ISBN: ";
    cin  >> ISBN;    

    if (addItem(ISBN, qty)) {
 
      qtys.push_back(qty);

      bool invalid = true;

      while (invalid) {
          
        cout <<"\n\nIs there another title for the same customer? (y/n) ";
        cin  >> again;

        if (again == 'N' || again == 'n') { done = true; invalid = false; }
        if (again == 'Y' || again == 'y') { done = false;  invalid = false; }
        if (again != 'N' && again != 'n' &&
           again != 'Y' && again != 'y') invalid = true;
      }
    }
    else cout << "\nFailed to add book to order.  Please check ISBN and try again.\n\n";

  }
  
  list<BookData>::iterator iter = order.begin();
  list<int>::iterator qiter = qtys.begin();  
//  if (!order.booksAvailable()) { /* do nothing right now */ }
//  else {

    cout << "\n\n\tSerendipity Book Sellers\nDate: ";
    cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << endl;

    cout << "QTY\tISBN\tTitle\t\tPrice\tTotal\n";
    cout << "--------------------------------------------------\n";
    double runningTotal = 0;

    for ( ; iter != order.end() ; *iter++) {

      cout << *qiter << '\t' << iter->getIsbn() << '\t';
      cout << iter->getTitle();
      cout <<"\t $" << iter->getRetail() << "\t $" << ((*qiter) * iter->getRetail()) << '\n';

      runningTotal += (*qiter) * iter->getRetail();
      qiter++;
    }

    double tax = runningTotal * 0.06;

    cout << "\n\n\tSubtotal:\t$" << runningTotal << endl;
    cout << "\tTax:\t\t$" << tax << endl;
    cout << "\tTotal:\t\t$" << runningTotal + tax << endl << endl;

    system("pause");
//  }  
}

bool Cashier::addItem(string ISBN, int qty) {

     list<BookData>::iterator it = bookCollection.lookupIsbn(ISBN); 

     order.push_back(it->bookReturn()); 
     return true;
}